// pages/login/login.js
const app = getApp();

Page({
  data: {
    userType: "student",
    username: "",
    password: "",
    loading: false,
    canLogin: false,
  },

  onLoad() {
    // 检查是否已登录
    if (app.globalData.userInfo) {
      this.redirectToHome();
    }
  },

  selectUserType(e) {
    const userType = e.currentTarget.dataset.type;
    this.setData({ userType });
    this.checkCanLogin();
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
    this.checkCanLogin();
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
    this.checkCanLogin();
  },

  checkCanLogin() {
    const { username, password } = this.data;
    this.setData({
      canLogin: username.trim() && password.trim(),
    });
  },

  async login() {
    if (!this.data.canLogin || this.data.loading) return;

    this.setData({ loading: true });

    try {
      const { userType, username, password } = this.data;
      const local = require("../../utils/local");
      const result = local.login({
        userType,
        username: username.trim(),
        password: password.trim(),
      });

      if (result.success) {
        app.login(result.userInfo, userType);

        wx.showToast({
          title: "登录成功",
          icon: "success",
        });

        setTimeout(() => {
          this.redirectToHome();
        }, 800);
      } else {
        wx.showToast({
          title: result.message || "登录失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("登录错误:", error);
      wx.showToast({
        title: "本地登录异常",
        icon: "error",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  redirectToHome() {
    const { userType } = this.data;

    if (userType === "student") {
      wx.switchTab({
        url: "/pages/student/profile/profile",
      });
    } else {
      wx.navigateTo({
        url: "/pages/judge/dashboard/dashboard",
      });
    }
  },

  goToRegister() {
    wx.navigateTo({
      url: "/pages/register/register",
    });
  },
});
